<template>
  <div class="file-search-box">
    <div class="search-box">
      <div class="search-content">
        <el-select v-model="searchType" placeholder="请选择">
          <el-option
            v-for="item in searchTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-input
          class="search-input"
          placeholder="请输入内容"
          v-model="searchVal"
        >
        </el-input>
        <el-button icon="el-icon-search" @click="search"></el-button>
      </div>
      <el-button type="primary" class="btn-lanse" @click="download">
        <i class="el-icon-download el-icon--left xz"></i>下载
      </el-button>
    </div>
    <!-- <div class="type-radio-box">
      <span class="tit">文件类型: </span>
      <el-radio v-model="typeRadioVal" label="0">word</el-radio>
      <el-radio v-model="typeRadioVal" label="1">pdf</el-radio>
    </div> -->
    <div class="list-box">
      <!-- 标题 -->
      <el-table
        class="title-table-box"
        v-show="searchListType == 1"
        ref="titleTabel"
        :data="tableData"
        style="width: 100%"
        row-key="rowId"
        :header-cell-style="{ background: '#F0F0F6', color: '#2D3548' }"
        @cell-click="handleCellClick"
      >
        <el-table-column
          type="selection"
          reserve-selection
          width="55"
        ></el-table-column>
        <el-table-column label="文件编号" class-name="tit-column" width="200">
          <template slot-scope="scope">
            <span v-html="scope.row.fileId"></span>
          </template>
        </el-table-column>
        <el-table-column label="文件名称" prop="fileName"></el-table-column>
        <el-table-column label="标题" class-name="tit-column">
          <template slot-scope="scope">
            <span v-html="scope.row.highlightTitle"></span>
          </template>
        </el-table-column>
      </el-table>
      <!-- 正文 -->
      <el-table
        v-show="searchListType == 2"
        ref="textTabel"
        :data="tableData"
        style="width: 100%"
        row-key="rowId"
        :header-cell-style="{ background: '#F0F0F6', color: '#2D3548' }"
      >
        <el-table-column
          type="selection"
          reserve-selection
          width="55"
        ></el-table-column>
        <el-table-column label="文件编号" class-name="tit-column" width="200">
          <template slot-scope="scope">
            <span v-html="scope.row.fileId"></span>
          </template>
        </el-table-column>
        <el-table-column label="文件名称" prop="fileName"></el-table-column>
        <el-table-column label="标题" width="230">
          <template slot-scope="scope">
            <span v-html="scope.row.highlightTitle"></span>
          </template>
        </el-table-column>
        <el-table-column label="正文内容">
          <template slot-scope="scope">
            <span v-html="scope.row.highlightText"></span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-box">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
        :current-page="currentPage"
        :page-sizes="[5, 10, 15]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalSize"
      >
      </el-pagination>
    </div>
    <el-dialog title="详情" :visible.sync="detailDialogVisible" width="40%">
      <el-tree
        v-if="detailDialogVisible"
        ref="tree"
        :props="props"
        :load="loadNode"
        lazy
      >
        <div
          slot-scope="{ node, data }"
          :class="data.type == -1 ? 'onlyThreeActive' : 'onlyThree'"
        >
          <span class="tree_label" :title="node.label">{{ node.label }}</span>
        </div>
      </el-tree>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchType: 1,
      searchVal: "",
      typeRadioVal: "0",
      searchTypeOptions: [
        {
          value: 1,
          label: "标题",
        },
        {
          value: 2,
          label: "正文",
        },
      ],
      tableData: [],
      pageSize: 10,
      totalSize: 0,
      currentPage: 1,
      searchListType: 1,
      detailDialogVisible: false,
      props: {
        label: "labelContent",
        children: "zones",
        isLeaf: "leaf",
      },
      clickCell: {},
    };
  },
  methods: {
    download() {
      let params = {
        keyword: this.searchVal,
      };
      if (this.searchType == "2") {
        let selectArr = this.$refs.textTabel.selection;
        if (!selectArr.length) {
          this.$message({
            type: "warning",
            message: "请勾选所需下载项",
          });
          return;
        }
        let str = "";
        selectArr.forEach((item) => {
          str += `${item.title}\n${item.content}\n`;
        });

        params.content = str;

        this.onFileSave(params);
      } else if (this.searchType == "1") {
        let selectArr = this.$refs.titleTabel.selection;
        if (!selectArr.length) {
          this.$message({
            type: "warning",
            message: "请勾选所需下载项",
          });
          return;
        }
        let str = "";
        let promiseArr = selectArr.map((item) => {
          let titleAllParams = {
            kind: this.typeRadioVal,
            title_id: item.rowId,
            file_id: item.fileId,
          };
          return new Promise((resolve) => {
            this.$api
              .title_all_search(titleAllParams)
              .then((res) => {
                let firstData = res.data;
                let tit = firstData.data.title
                  ? firstData.data.title
                  : firstData.data.text;
                str += `${tit}\n`;

                digui(firstData.children);

                resolve();

                function digui(data) {
                  data.forEach((item) => {
                    let tit = item.data.title
                      ? item.data.title
                      : item.data.text;
                    str += `${tit}\n`;
                    if (item.data.type == -1) return;
                    digui(item.children);
                  });
                }
              })
              .catch((err) => {
                this.$message({
                  type: "warning",
                  message: err.msg,
                });
                resolve();
              });
          });
        });

        Promise.all(promiseArr).then(() => {
          params.content = str;
          this.onFileSave(params);
        });
      }
    },
    onFileSave(params) {
      this.$api.fileSave(params).catch((res) => {
        const blog = new Blob([res.data], {
          type: "application/msword;charset=utf-8",
        });
        const url = window.URL.createObjectURL(blog);
        let body = document.querySelector("body");
        let link = document.createElement("a");
        link.href = url;
        link.download = `${params.keyword}_下载`;
        link.style.display = "none";
        body.appendChild(link);
        link.click();
        body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
      });
    },
    highlight(str) {
      let highlightStr = str.replace(
        new RegExp(this.searchVal, "gm"),
        `<span style='color: red;'>${this.searchVal}</span>`
      );
      return highlightStr;
    },
    search() {
      if (!this.searchVal) {
        this.$message({
          type: "warning",
          message: "请输入内容",
        });
        return;
      }
      this.$refs.textTabel.clearSelection([]);
      this.$refs.titleTabel.clearSelection([]);
      this.currentPage = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList();
    },
    getList() {
      let params = {
        kind: this.typeRadioVal,
        from: this.currentPage,
        size: this.pageSize,
      };
      let apiName = "";
      if (this.searchType == 1) {
        apiName = "title_retrieval";
        params.title = this.searchVal;
      } else {
        apiName = "text_retrieval";
        params.text = this.searchVal;
      }

      let fileIdsArr = [];
      this.$api[apiName](params).then((res) => {
        let data = res.data;
        this.totalSize = res.total || 0;
        this.searchListType = this.searchType;
        if (this.searchType == 2) {
          // 正文
          let listArr = [];
          data.forEach((item, index) => {
            let highlightTitle = this.highlight(item.title.title);
            let highlightText = this.highlight(item.text.text);
            fileIdsArr.push(item.title.file_id);
            listArr.push({
              rowId: item.title.uuid + index,
              title: item.title.title,
              content: item.text.text,
              highlightTitle,
              highlightText,
              fileId: item.title.file_id,
            });
          });
          this.$api.getFileNames(fileIdsArr).then((res) => {
            listArr.forEach((item) => {
              item.fileName = res.data[item.fileId];
            });
            this.tableData = listArr;
          });
        } else {
          // 标题
          let listArr = [];
          data.forEach((item) => {
            let highlightTitle = this.highlight(item.data.title);
            fileIdsArr.push(item.data.file_id);
            listArr.push({
              rowId: item.data.uuid,
              title: item.data.title,
              highlightTitle,
              fileId: item.data.file_id,
              nextLevelData: item.children,
            });
          });
          this.$api.getFileNames(fileIdsArr).then((res) => {
            listArr.forEach((item) => {
              item.fileName = res.data[item.fileId];
            });
            this.tableData = listArr;
          });
        }
      });
    },
    handleCellClick(row) {
      this.clickCell = row;
      this.detailDialogVisible = true;
    },
    loadNode(node, resolve) {
      let fileType = this.typeRadioVal;
      let apiName = "";
      if (fileType == "0") {
        apiName = "get_word_info";
      } else {
        apiName = "get_pdf_info";
      }

      if (node.level === 0) {
        let treeData = [
          {
            labelContent: this.clickCell.title,
            leaf: false,
            zones: [],
          },
        ];
        return resolve(treeData);
      }
      let obj2 = {};
      if (node.level >= 1) {
        if (node.level == 1) {
          obj2 = {
            file_id: this.clickCell.fileId,
            uuid: this.clickCell.rowId,
          };
        } else {
          obj2 = {
            file_id: node.data.file_id,
            uuid: node.data.uuid,
          };
        }
        this.$api[apiName](obj2)
          .then((res) => {
            res.data.forEach((item, i) => {
              let type = item.type == -1 ? true : false;
              item.leaf = type;
              item.labelContent = item.title ? item.title : item.text;
            });
            return resolve(res.data);
          })
          .catch((err) => {
            {
              this.$message({
                type: "error",
                message: err.msg,
              });
            }
          });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.file-search-box {
  padding: 0 30px;
  .search-box {
    display: flex;
    justify-content: space-between;
    padding-top: 20px;
    /deep/ .search-content {
      display: flex;
      .el-select {
        width: 80px;
        .el-input__inner {
          border-right: none;
          border-top-right-radius: 0;
          border-bottom-right-radius: 0;
        }
      }
      .search-input {
        width: 300px;
        .el-input__inner {
          border-top-left-radius: 0;
          border-bottom-left-radius: 0;
        }
      }
      .el-button {
        color: #fff;
        background-color: #409eff;
        border-color: #409eff;
        margin-left: 10px;
      }
    }
  }
  .type-radio-box {
    padding-top: 10px;
    .tit {
      font-size: 14px;
      margin-right: 15px;
    }
  }
  .list-box {
    padding-top: 20px;
  }
  .page-box {
    padding: 40px 0;
    text-align: right;
  }
  /deep/ .title-table-box {
    .tit-column {
      cursor: pointer;
    }
  }
}
</style>

<style lang="scss">
.el-tree-node__content {
  height: auto !important;
}
.el-tree {
  height: 440px;
  padding: 20px;
  overflow: auto;
}
.onlyThree {
  width: 100%;
  font-weight: bold;
  overflow: hidden;
  text-overflow: ellipsis; //显示为省略号
  white-space: nowrap; //不换行
  text-align: left;
  span {
    white-space: pre-wrap;
  }
}
.onlyThreeActive {
  width: 100%;
  font-size: 16px;
  overflow: hidden;
  text-overflow: ellipsis; //显示为省略号
  white-space: nowrap; //不换行
  text-align: left;
  span {
    white-space: pre-wrap;
  }
}
</style>
